﻿using ZhCun.SerialIO;
using ZhCun.SerialIO.Utils;

namespace SerialIoDemo.FixedHead.ProtocolModel
{
    /// <summary>
    /// 发送(写)串口数据的实体基类
    /// </summary>
    public abstract class W_Base : BaseProtocol, IWriteModel
    {
        public W_Base()
        {
            EncodeHelper = new BytesEncode();
        }
        /// <summary>
        /// 编码帮助类
        /// </summary>
        protected BytesEncode EncodeHelper { get; private set; }
        /// <summary>
        /// 已经编码的当前命令数据
        /// </summary>
        public byte[] CommandData { private set; get; }

        /// <summary>
        /// set body 数据
        /// </summary>
        /// <param name="encode"></param>
        protected abstract void SetBodyData(BytesEncode encode);
        /// <summary>
        /// 命令字
        /// </summary>
        protected abstract byte CmdWord { get; }
        /// <summary>
        /// 得到该实体类的命令数据流
        /// </summary>
        public byte[] GetData()
        {
            //[0xaa,0xbb] [len] [cmd] [DevId] [data] [crc-1,crc-2]        
            EncodeHelper.ClearData();
            EncodeHelper.AddBytes(PackHead);
            EncodeHelper.AddByte(0); //长度，获取body后再赋值
            EncodeHelper.AddByte(CmdWord);
            EncodeHelper.AddByte(DevId);//设备号

            SetBodyData(EncodeHelper);

            int count = EncodeHelper.GetResultCount();
            EncodeHelper.SetValue(2, (byte)(count + 2)); //设置包长（包含校验码）
            var data = EncodeHelper.GetResult();
            var crc = GetCRC(data.ToArray(), 0, data.Count);
            EncodeHelper.AddUInt16(crc, true);
            CommandData = EncodeHelper.GetResult().ToArray();
            return CommandData;
        }
    }
}
